package com.zpark.wxshop.controller;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.sql.Timestamp;
import java.util.Date;
import java.util.List;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zpark.wxshop.Utils.Result;

import com.zpark.wxshop.service.IAddressService;
import com.zpark.wxshop.entity.Address;

import org.springframework.web.bind.annotation.RestController;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author PJone
 * @since 2023-09-04
 */
@RestController
@RequestMapping("/address")
public class AddressController {

    @Resource
    private IAddressService addressService;

    /**
    * 新增与修改
    */
    @PostMapping
    public Result save(@RequestBody Address address) {
        if (address.getAid() == null){
            address.setCreatedTime(new Timestamp(new Date().getTime()));
            address.setCreatedUser(address.getName());
        }

        address.setModifiedTime(new Timestamp(new Date().getTime()));
        address.setModifiedUser(address.getName());
        addressService.saveOrUpdate(address);
        return Result.success();
    }

    /**
    * 根据id删除
    */
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {
        addressService.removeById(id);
        return Result.success();
    }

    /**
    * 批量删除
    */
    @PostMapping("/del/batch")
    public Result deleteBatch(@RequestBody List<Integer> ids) {
        addressService.removeByIds(ids);
        return Result.success();
    }

    /**
    * 查询所有
    */
    @GetMapping
    public Result findAll() {
        return Result.success(addressService.list());
    }

    /**
    * 根据id查询单个
    */
    @GetMapping("/{id}")
    public Result findOne(@PathVariable Integer id) {
        return Result.success(addressService.getById(id));
    }

    /**
    * 分页查询
    */
    @GetMapping("/page")
    public Result findPage(@RequestParam Integer pageNum,
                                @RequestParam Integer pageSize) {
        QueryWrapper<Address> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("id");
        return Result.success(addressService.page(new Page<>(pageNum, pageSize), queryWrapper));
    }

    /**
     * 根据用户id查询地址列表
     */
    @GetMapping("/list_by_uid/{uid}")
    public Result findByUid(@PathVariable("uid") Integer uid){
        return Result.success(addressService.list(new QueryWrapper<Address>().eq("uid", uid)));
    }

    /**
     * 查询用户默认地址
     */
    @GetMapping("/DeAddress/{uid}")
    public Result findDeAddressByUid(@PathVariable("uid") Integer uid){
        return Result.success(addressService.getOne(new QueryWrapper<Address>().eq("uid", uid).eq("is_default", 1)));
    }

}

